package org.ch00.test14;

import java.util.LinkedList;

/**
 * 篮子 - 装水果
 *
 * @author ZQX
 * @date 2025-03-14
 */
public class Box {

    /**
     * 篮子容器
     */
    private LinkedList<Fruit> boxList = new LinkedList<>();

    /**
     * 定义常量 - 表达篮子最大容量
     */
    private static final int MAX_SIZE = 5;


    /**
     * 男孩放水果
     *
     * @param name  男孩的姓名
     * @param fruit 水果名称
     */
    public synchronized void put(String name, Fruit fruit) {
        while (boxList.size() == MAX_SIZE) {
            this.notifyAll();
            try {
                System.out.println("篮子满了");
                System.out.println("-----------------");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        boxList.add(fruit);
        System.out.println(name + "把" + fruit.toString() + "放入篮子");
        System.out.println("篮子剩余空间" + (MAX_SIZE - boxList.size()));
        System.out.println("-----------------");
        notifyAll();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 女孩取水果
     *
     * @param name 女孩的名称
     * @return
     */
    public synchronized void take(String name) {
        while (boxList.size() == 0) {
            try {
                wait();
                System.out.println(name + "取水果，没有水果了");
                System.out.println("-----------------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Fruit fruit = boxList.removeLast();
        System.out.println(name + "把" + fruit.toString() + "取出篮子");
        System.out.println("篮子剩余空间" +  (MAX_SIZE - boxList.size()));
        System.out.println("-----------------");
        notifyAll();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();}
    }
}
